package com.novaed.game.panels;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.novaed.game.backend.ImagePanel;
import com.novaed.game.backend.Paths;
import com.novaed.game.backend.Player;
import com.novaed.game.backend.Profile;
import com.novaed.game.frames.WindowMain;

@SuppressWarnings("serial")
public class Home extends JPanel implements ActionListener {
	
	private Player player = new Player();
	private Profile online;
	
	WindowMain w;

	/**
	 * Create the panel.
	 */
	public Home() {
		
		HOME = new ImagePanel(bg_menu);
		
		emb_login = new ImageIcon("./res/imgs/menu/emboss/login.png");
		emb_register = new ImageIcon("./res/imgs/menu/emboss/register.png");
		emb_board = new ImageIcon("./res/imgs/menu/emboss/board.png");
		emb_options = new ImageIcon("./res/imgs/menu/emboss/option.png");
		emb_credits = new ImageIcon("./res/imgs/menu/emboss/credits.png");
		emb_exit = new ImageIcon("./res/imgs/menu/emboss/exit.png");

		flt_login = new ImageIcon("./res/imgs/menu/flat/login.png");
		flt_register = new ImageIcon("./res/imgs/menu/flat/register.png");
		flt_board = new ImageIcon("./res/imgs/menu/flat/board.png");
		flt_options = new ImageIcon("./res/imgs/menu/flat/option.png");
		flt_credits = new ImageIcon("./res/imgs/menu/flat/credits.png");
		flt_exit = new ImageIcon("./res/imgs/menu/flat/exit.png");

		roll_login = new ImageIcon("./res/imgs/menu/roll/login.png");
		roll_register = new ImageIcon("./res/imgs/menu/roll/register.png");
		roll_board = new ImageIcon("./res/imgs/menu/roll/board.png");
		roll_options = new ImageIcon("./res/imgs/menu/roll/option.png");
		roll_credits = new ImageIcon("./res/imgs/menu/roll/credits.png");
		roll_exit = new ImageIcon("./res/imgs/menu/roll/exit.png");

		int strt_height = 5;

		GridBagLayout gbl_HOME = new GridBagLayout();
		gbl_HOME.columnWidths = new int[]{25, 0, 0};
		gbl_HOME.rowHeights = new int[]{140, 0, 0, 0, 0, 0, 0, 
				0, 0, 0, 0, 0, 0};
		gbl_HOME.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
		gbl_HOME.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
				0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};

		HOME.setLayout(gbl_HOME);

		btn_Login = new JButton(emb_login);
		btn_Login.setPressedIcon(flt_login);
		btn_Login.setRolloverIcon(roll_login); 

		GridBagConstraints gbc_BTNLogin = new GridBagConstraints();
		gbc_BTNLogin.insets = new Insets(0, 0, 5, 0);
		gbc_BTNLogin.fill = GridBagConstraints.BOTH;
		gbc_BTNLogin.gridx = 1;
		gbc_BTNLogin.gridy = 1;
		HOME.add(btn_Login, gbc_BTNLogin);

		Component verticalStrut = Box.createVerticalStrut(strt_height-3);
		GridBagConstraints gbc_verticalStrut = new GridBagConstraints();
		gbc_verticalStrut.fill = GridBagConstraints.HORIZONTAL;
		gbc_verticalStrut.insets = new Insets(0, 0, 5, 0);
		gbc_verticalStrut.gridx = 1;
		gbc_verticalStrut.gridy = 2;
		HOME.add(verticalStrut, gbc_verticalStrut);

		btn_Register = new JButton(emb_register);
		btn_Register.setPressedIcon(flt_register);
		btn_Register.setRolloverIcon(roll_register); 

		GridBagConstraints gbc_BTNRegister = new GridBagConstraints();
		gbc_BTNRegister.insets = new Insets(0, 0, 5, 0);
		gbc_BTNRegister.fill = GridBagConstraints.BOTH;
		gbc_BTNRegister.gridx = 1;
		gbc_BTNRegister.gridy = 3;
		HOME.add(btn_Register, gbc_BTNRegister);

		Component verticalStrut_1 = Box.createVerticalStrut(strt_height-3);
		GridBagConstraints gbc_verticalStrut_1 = new GridBagConstraints();
		gbc_verticalStrut_1.fill = GridBagConstraints.HORIZONTAL;
		gbc_verticalStrut_1.insets = new Insets(0, 0, 5, 0);
		gbc_verticalStrut_1.gridx = 1;
		gbc_verticalStrut_1.gridy = 4;
		HOME.add(verticalStrut_1, gbc_verticalStrut_1);

		btn_Board = new JButton(emb_board);
		btn_Board.setPressedIcon(flt_board);
		btn_Board.setRolloverIcon(roll_board); 

		btn_Board.setOpaque(false);
		GridBagConstraints gbc_BTNBoard = new GridBagConstraints();
		gbc_BTNBoard.insets = new Insets(0, 0, 5, 0);
		gbc_BTNBoard.fill = GridBagConstraints.BOTH;
		gbc_BTNBoard.gridx = 1;
		gbc_BTNBoard.gridy = 5;
		HOME.add(btn_Board, gbc_BTNBoard);

		Component verticalStrut_2 = Box.createVerticalStrut(strt_height);
		GridBagConstraints gbc_verticalStrut_2 = new GridBagConstraints();
		gbc_verticalStrut_2.fill = GridBagConstraints.HORIZONTAL;
		gbc_verticalStrut_2.insets = new Insets(0, 0, 5, 0);
		gbc_verticalStrut_2.gridx = 1;
		gbc_verticalStrut_2.gridy = 6;
		HOME.add(verticalStrut_2, gbc_verticalStrut_2);

		btn_Options = new JButton(emb_options);
		btn_Options.setPressedIcon(flt_options);
		btn_Options.setRolloverIcon(roll_options); 

		GridBagConstraints gbc_BTNOptions = new GridBagConstraints();
		gbc_BTNOptions.insets = new Insets(0, 0, 5, 0);
		gbc_BTNOptions.fill = GridBagConstraints.BOTH;
		gbc_BTNOptions.gridx = 1;
		gbc_BTNOptions.gridy = 7;
		HOME.add(btn_Options, gbc_BTNOptions);

		Component verticalStrut_3 = Box.createVerticalStrut(strt_height);
		GridBagConstraints gbc_verticalStrut_3 = new GridBagConstraints();
		gbc_verticalStrut_3.fill = GridBagConstraints.HORIZONTAL;
		gbc_verticalStrut_3.insets = new Insets(0, 0, 5, 0);
		gbc_verticalStrut_3.gridx = 1;
		gbc_verticalStrut_3.gridy = 8;
		HOME.add(verticalStrut_3, gbc_verticalStrut_3);

		btn_Credits = new JButton(emb_credits);
		btn_Credits.setPressedIcon(flt_credits);
		btn_Credits.setRolloverIcon(roll_credits); 

		GridBagConstraints gbc_BTNCredits = new GridBagConstraints();
		gbc_BTNCredits.fill = GridBagConstraints.HORIZONTAL;
		gbc_BTNCredits.insets = new Insets(0, 0, 5, 0);
		gbc_BTNCredits.gridx = 1;
		gbc_BTNCredits.gridy = 9;
		HOME.add(btn_Credits, gbc_BTNCredits);

		Component verticalStrut_4 = Box.createVerticalStrut(strt_height-3);
		GridBagConstraints gbc_verticalStrut_4 = new GridBagConstraints();
		gbc_verticalStrut_4.fill = GridBagConstraints.HORIZONTAL;
		gbc_verticalStrut_4.insets = new Insets(0, 0, 5, 0);
		gbc_verticalStrut_4.gridx = 1;
		gbc_verticalStrut_4.gridy = 10;
		HOME.add(verticalStrut_4, gbc_verticalStrut_4);

		btn_Exit = new JButton(emb_exit);
		btn_Exit.setPressedIcon(flt_exit);
		btn_Exit.setRolloverIcon(roll_exit); 

		GridBagConstraints gbc_BTNExit = new GridBagConstraints();
		gbc_BTNExit.fill = GridBagConstraints.BOTH;
		gbc_BTNExit.gridx = 1;
		gbc_BTNExit.gridy = 11;
		HOME.add(btn_Exit, gbc_BTNExit);

		List <JButton> buttons = new ArrayList<JButton>();
		buttons.add(btn_Login);
		buttons.add(btn_Register);
		buttons.add(btn_Board);
		buttons.add(btn_Options);
		buttons.add(btn_Credits);
		buttons.add(btn_Exit);

		for (JButton j : buttons) {
			j.setOpaque(false);
			j.setRolloverEnabled(true);
			j.setBorderPainted(false);  
			j.setFocusPainted(false);  
			j.setContentAreaFilled(false);
			j.addActionListener(this);
		}
		
		HOME.setVisible(true);
		setLayout(new BorderLayout(0, 0));
		add(HOME);
	}
	
	
	public void doLogin() {

		// =========================================================================== Layout
		final JTextField txt_username;
		JPasswordField txt_password;
		JPanel login = new JPanel();

		GridBagLayout gbl_login = new GridBagLayout();
		gbl_login.columnWidths = new int[]{0, 0, 0, 0};
		gbl_login.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
		gbl_login.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
		gbl_login.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		login.setLayout(gbl_login);

		JLabel lbl_username = new JLabel("Username :");
		GridBagConstraints gbc_lbl_username = new GridBagConstraints();
		gbc_lbl_username.insets = new Insets(0, 0, 5, 5);
		gbc_lbl_username.gridx = 0;
		gbc_lbl_username.gridy = 1;
		login.add(lbl_username, gbc_lbl_username);

		JLabel novaed = new JLabel("novaed-");
		GridBagConstraints gbc_novaed = new GridBagConstraints();
		gbc_novaed.insets = new Insets(0, 0, 5, 5);
		gbc_novaed.gridx = 1;
		gbc_novaed.gridy = 1;
		login.add(novaed, gbc_novaed);

		txt_username = new JTextField();
		txt_username.setColumns(10);
		GridBagConstraints gbc_txt_username = new GridBagConstraints();
		gbc_txt_username.insets = new Insets(0, 0, 5, 0);
		gbc_txt_username.fill = GridBagConstraints.HORIZONTAL;
		gbc_txt_username.gridx = 2;
		gbc_txt_username.gridy = 1;
		login.add(txt_username, gbc_txt_username);

		JLabel lbl_password = new JLabel("Password :");
		GridBagConstraints gbc_lbl_password = new GridBagConstraints();
		gbc_lbl_password.insets = new Insets(0, 0, 5, 5);
		gbc_lbl_password.gridx = 0;
		gbc_lbl_password.gridy = 2;
		login.add(lbl_password, gbc_lbl_password);

		txt_password = new JPasswordField();
		txt_password.setColumns(10);
		GridBagConstraints gbc_txt_password = new GridBagConstraints();
		gbc_txt_password.gridwidth = 2;
		gbc_txt_password.insets = new Insets(0, 0, 5, 0);
		gbc_txt_password.fill = GridBagConstraints.HORIZONTAL;
		gbc_txt_password.gridx = 1;
		gbc_txt_password.gridy = 2;
		login.add(txt_password, gbc_txt_password);

		int result = JOptionPane.showConfirmDialog(null, login, 
				"Login to Game", JOptionPane.OK_CANCEL_OPTION);

		// =========================================================================== LogIn Code

		if (result == JOptionPane.OK_OPTION) {

			Node profile = null;
			Element user = null;
			
			String uname = txt_username.getText();
			String pword = String.valueOf(txt_password.getPassword());

			ArrayList<String> usernames = new ArrayList<String>();
			ArrayList<String> passwords = new ArrayList<String>();

			
			try {

				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				Document doc = dBuilder.parse(Paths.getUsers());

				doc.getDocumentElement().normalize();

				NodeList profilesList = doc.getElementsByTagName("profile");

				for (int i = 0; i <= profilesList.getLength()-1; i++) {

					profile = profilesList.item(i);
					user = (Element) profile;
					usernames.add(user.getElementsByTagName("username").item(0).getTextContent());
					passwords.add(user.getElementsByTagName("password").item(0).getTextContent());

					// username : password
					if (usernames.get(i).toString().equals(uname)) {
						
						if (passwords.get(i).toString().equals(pword)) {

						online = new Profile(txt_username.getText(), 
											user.getAttribute("pid"));

						System.out.println("ProfileID : " + user.getAttribute("pid"));
						System.out.println("Username : novaed" + user.getElementsByTagName("username").item(0).getTextContent());
						System.out.println("Password : " + user.getElementsByTagName("password").item(0).getTextContent());
						System.out.println("Registered to : " 
											+ user.getElementsByTagName("firstname").item(0).getTextContent()
											+ " "
											+ user.getElementsByTagName("lastname").item(0).getTextContent());
						System.out.println(online.getScoreSheet());
						System.out.println("Levels played : " + online.getRawScores());
						System.out.println("PCT: " + online.getPercentage());
						System.out.println("Number of times played : " + online.getTimesPlayed());
						System.out.println("Total score : " + online.getTotalScore());
						online.setOnlineUser(txt_username.getText());
						
						System.out.println("login " + online.getOnlineUser());
						
						JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
						topFrame.setTitle("Welcome, " + user.getElementsByTagName("firstname").item(0).getTextContent() + " !");
						//TODO here
						Play p = new Play();
						topFrame.removeAll();
						topFrame.add(p).setVisible(true);
						p.setVisible(true);
						HOME.setVisible(false);
						
						
						break;
						
						} else {
							System.err.println("username or password error!");
							break;
						}
					} 
				}
				
			} catch (SAXException e) {
				System.err.println(e);
			} catch (IOException e) {
				System.err.println(e);
			} catch (ParserConfigurationException e) {
				System.err.println(e);
			} catch (NullPointerException e) {
				System.err.println(e);
			}
		} else {
//			dispose();
			
			//FIXME found error here
		}
		
	}
	
	public void doLogout() {

//		int result = JOptionPane.showConfirmDialog(this, "Do you want to leave the game now?", "Exit",
//				JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
//
//		if (result == JOptionPane.YES_OPTION) {
//			System.exit(0);
//		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if (e.getSource() == btn_Login) {
			doLogin();
		}
		if (e.getSource() == btn_Register) {
		}
		if (e.getSource() == btn_Board) {
		}
		if (e.getSource() == btn_Options) {
		}
		if (e.getSource() == btn_Exit) {
			doLogout();
		}
		
	}
	
	public String getOnlineUser() {
		System.out.println("home " + online.getOnlineUser());
		return this.online.getOnlineUser();
	}
	
	/*
	 * frame and panels
	 * */
	
	private JPanel HOME = null;


	/*
	 * background images
	 * 
	 * */

	private String bg_menu = "res/imgs/menu/bg_menu.png";

	/*
	 * button images
	 * 
	 * */

	private ImageIcon emb_login = null;
	private ImageIcon emb_register = null;
	private ImageIcon emb_board = null;
	private ImageIcon emb_options = null;
	private ImageIcon emb_credits = null;
	private ImageIcon emb_exit = null;

	private ImageIcon flt_login = null;
	private ImageIcon flt_register = null;
	private ImageIcon flt_board = null;
	private ImageIcon flt_options = null;
	private ImageIcon flt_credits = null;
	private ImageIcon flt_exit = null;

	private ImageIcon roll_login = null;
	private ImageIcon roll_register = null;
	private ImageIcon roll_board = null;
	private ImageIcon roll_options = null;
	private ImageIcon roll_credits = null;
	private ImageIcon roll_exit = null;
	
	/*
	 * buttons
	 * */
	private JButton btn_Login = null;
	private JButton btn_Register = null;
	private JButton btn_Board = null;
	private JButton btn_Options = null;
	private JButton btn_Credits = null;
	private JButton btn_Exit = null;
	
}
